package cc.android.testapp.ui.inject;

import android.view.View;

import java.lang.reflect.Field;

import cc.commons.util.reflect.FieldUtil;

public class ViewInject {
    /**
     * 为pParent所有注释过{#InjectView}的字段注入实例并设置监听器
     *
     * @param pParent 注入字段的实例
     * @param pGet    实现findViewById的方法
     * @param pLis    监听器
     */
    public static void injectView(Object pParent, FindViewById pGet, View.OnClickListener pLis) {
        for (Field sField : pParent.getClass().getDeclaredFields()) {
            InjectView tAnno = sField.getAnnotation(InjectView.class);
            if (tAnno == null) continue;
            View tView = pGet.getView(tAnno.id());
            if (tView == null) continue;
            if (sField.getType().isInstance(tView)) FieldUtil.setFieldValue(sField, pParent, tView);

            if (tAnno.addClickListener() && pLis != null) tView.setOnClickListener(pLis);
        }
    }

    public static interface FindViewById {
        View getView(int id);
    }
}
